
const math = require('mathjs')
const datajs = require('./data')



const deliveryOrders = datajs.data.deliveryOrders

let res = {
    code: '9999',
    data: {
    }, info: null
}


if (deliveryOrders.length >= 0) {
    for (let i = 0; deliveryOrders.length > i; i++) {
        let obj = deliveryOrders[i]
        for (let key in obj) {
            if ('idealFee' == key) {
                if (obj[key] != null) {
                    res.data.countFee = math.evaluate(`${res.data.countFee == null ? 0 : res.data.countFee}+${obj[key]}`)
                }
            }
        }
    }
    // res.data.deliveryGroup = sortClass(deliveryOrders)
    res.data.deliveryGroupCountFee = groupByName(deliveryOrders)
    console.log(JSON.stringify(res));
}






/**
 * 分组
 * @param {*} sortData 
 */
function sortClass(sortData) {
    const groupBy = (array, f) => {
        let groups = {};
        array.forEach((o) => {
            let group = JSON.stringify(f(o));
            groups[group] = groups[group] || [];
            groups[group].push(o);
        });
        return Object.keys(groups).map((group) => {
            return groups[group];
        });
    };
    const sorted = groupBy(sortData, (item) => {
        return item.driverName; // 返回需要分组的对象
    });
    return sorted;
};


/**
 * 分组统计数据
 * @param {} groupData 
 */
function groupByName(groupData) {
    let result = groupData.reduce((prevValue, currentValue) => {
        let index = -1;
        prevValue.some((item, i) => {
            if (item.driverName == currentValue.driverName) {
                index = i;
                return true;
            }
        })
        if (index > -1) {
            if (currentValue.idealFee != null) {
                prevValue[index].idealFee = math.evaluate(`${prevValue[index].idealFee}+${currentValue.idealFee}`)
            }
            prevValue[index].driverNumber = math.evaluate(`${prevValue[index].driverNumber}+1`)
            prevValue[index].driverOutNumber = math.evaluate(`${prevValue[index].driverOutNumber}+${currentValue.orderType == "asOrder" ? 1 : 0}`)
            prevValue[index].driverLoseNumber = math.evaluate(`${prevValue[index].driverLoseNumber}+${currentValue.orderState == 99 ? 1 : 0}`)
        } else {
            prevValue.push({
                driverName: currentValue.driverName,
                driverPhone: currentValue.driverPhone,
                driverNumber: 1,  // 总单数
                driverOutNumber: currentValue.orderType == "asOrder" ? 1 : 0, //  退货单- 已完成
                driverLoseNumber: currentValue.orderState == 99 ? 1 : 0, // 已取消
                idealFee: currentValue.idealFee // 总金额
            })
        }
        return prevValue;
    }, []);
    return result;
}